%% Set Parameters
clear all;clc;close all;
w=0.3;c1=2;c2=2;    
Bound=[-6 6; -6 6];
PopSize=15; MaxIteration=50;  
%% Step1 initlized
ProDim=size(Bound,1);
Margin=repmat((Bound(:,2)-Bound(:,1))',PopSize,1);
V=(rand(PopSize,ProDim)-0.5).*Margin;
X=rand(PopSize,ProDim).*Margin+repmat(Bound(:,1)',PopSize,1);
[pbest id]=min(fitfun(X));
Xpbest=X(id,:);       Xgbest=Xpbest;    gbest=pbest;
%% Step update
N=0;MatPbest=[];MatGbest=zeros(1,MaxIteration);
while(N<MaxIteration)
    N=N+1;
    V=w*V+c1*rand(size(X)).*(repmat(Xpbest,size(X,1),1)-X)+c2*rand(size(X)).*(repmat(Xgbest,size(X,1),1)-X);
    X=X+V;    
%check is particle out of bound
for i=1:size(X,1)
    for j=1:size(X,2)
        if(X(i,j)<Bound(j,1)||X(i,j)>Bound(j,2))
            X(i,j)=X(i,j)-V(i,j);
        end
    end      
end
[pbest id]=min(fitfun(X));
Xpbest=X(id,:);      

if(pbest<gbest)
    gbest=pbest;
     Xgbest=Xpbest;
end
MatGbest(N)=gbest;
figure(1)
plot(1:N,log(MatGbest(1:N)),'--bo','LineWidth',2,...
                'MarkerEdgeColor','k',...
                'MarkerFaceColor','g',...
                'MarkerSize',8);
set(gca,'fontsize',14);xlabel('Generation');ylabel('ln(Gbest)')
legend('G_b_e_s_t'); 
title(['Pbest=' num2str(gbest)]);
drawnow;            
end
%%
